/*
  Based on http://saju.net.in/code/misc/openssl_aes.c.txt
*/


#include <openssl/evp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "crypt.h"

#define DEFAULT_KEY "aaaabbbbccccddddeeeeffffgggghhh"

void gen_key (int key_len, unsigned char *key) {
  int i;
//  strcpy ((char *)key, DEFAULT_KEY);

  for (i=0; i<key_len; i++) {
    key[i] = (rand()*255)/RAND_MAX;
  }
}

void aes_encrypt (unsigned char *key, unsigned char *iv, 
                    unsigned char *plaintext, int plaintext_len, 
                    unsigned char *ciphertext, int *outlen) {
  int t;
  EVP_CIPHER_CTX ctx;
  EVP_EncryptInit (&ctx, EVP_aes_256_cbc(), key, iv);
  EVP_EncryptUpdate (&ctx, ciphertext, outlen, plaintext, plaintext_len);
  EVP_EncryptFinal (&ctx, ciphertext+(*outlen), &t);
  *outlen = *outlen + t;
}


void aes_decrypt (unsigned char *key, unsigned char *iv, 
                    unsigned char *ciphertext, int ciphertext_len, 
                    unsigned char *plaintext, int *outlen) {
  int t;
  EVP_CIPHER_CTX ctx;
  EVP_DecryptInit (&ctx, EVP_aes_256_cbc(), key, iv);
  EVP_DecryptUpdate (&ctx, plaintext, outlen, ciphertext, ciphertext_len);
  EVP_DecryptFinal (&ctx, plaintext+(*outlen), &t);
  *outlen = *outlen + t;
}

